package m.jclecai.com.activity;

import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.adapter.RecordAdapter;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.GroupBuyBean;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.ui.BetSSQ_DLT_QLCActivity;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.utils.http.responseBody.GroupBuyBody;
import m.jclecai.com.view.MyAutoLoopWheel;

/**
 * 投注记录
 */
public class VoteRecordActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener2
        , AdapterView.OnItemClickListener {

    @BindView(R.id.pr_listview)
    PullToRefreshListView pr_listview;
    @BindView(R.id.rg_count)
    RadioGroup rgCount;
    @BindView(R.id.ll_empty)
    LinearLayout ll_empty;
    @BindView(R.id.lw_loop)
    MyAutoLoopWheel lwLoop;
    @BindView(R.id.tv_touzhu)
    TextView tv_touzhu;
    @BindView(R.id.tv_desc)
    TextView tvDesc;


    private int index = 0; //0-购买记录 1-追号记录 2-合买记录
    UserBean userBean;
    RecordAdapter adapter;
    List<GroupBuyBean> records;
    int page = 1;
    String result = "all";

    @Override
    public int getContentView() {
        return R.layout.activity_vote_record;
    }

    @Override
    public void initView() {
        leftOptionText("");

        setTitle(getIntent().getStringExtra("title"));
        index = getIntent().getIntExtra("index", 0);
        ll_empty.setVisibility(View.GONE);
        tv_touzhu.setVisibility(View.GONE);
        showLoadingLayout(pr_listview);
    }

    @Override
    public void initData() {
        checkLogin(new Callback(){

            @Override
            public void callbackField() {
                super.callbackField();
                VoteRecordActivity.this.finish();
            }

            @Override
            public void callbackSuccess() {
                super.callbackSuccess();
                init();
            }
        });
    }

    private void init() {
        records = new ArrayList<>();
        userBean = PreferenceUtil.readUser(this);
        adapter = new RecordAdapter(this, records, index);
        pr_listview.setAdapter(adapter);
        pr_listview.setOnRefreshListener(this);
        pr_listview.setOnItemClickListener(this);
        pr_listview.setMode(PullToRefreshBase.Mode.BOTH);
        pr_listview.setEmptyView(ll_empty);
        if (lwLoop.isSsq())
            tvDesc.setText(("来注双色球，2元可变1000w"));
        else
            tvDesc.setText(("来注大乐透，2元可变1000w"));
        getData();
    }

    @Override
    protected void initListener() {
        super.initListener();
        lwLoop.setCallback(new Callback() {
            @Override
            public void callbackSuccess() {
                super.callbackSuccess();
                //这里是有可能空指针异常的；
                if (tv_touzhu != null) {
                    tv_touzhu.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @OnClick(R.id.tv_touzhu)
    void touzhu() {
        startActivity(new Intent(this, BetSSQ_DLT_QLCActivity.class).
                putExtra("redBall", JSON.toJSONString(lwLoop.getRedArr())).
                putExtra("blueBall", JSON.toJSONString(lwLoop.getBlueArr())).
                putExtra("type", lwLoop.isSsq() ? "ssq" : "dlt"));

//        Intent intent = new Intent(this, BetConfirmActivity.class);
//        intent.putExtra("type", lwLoop.isSsq() ? "ssq" : "dlt"); //彩种
//        intent.putExtra("totalMoney", 2); //总金额
//        intent.putExtra("totalNum", 1); //总注数
//        intent.putStringArrayListExtra("ballNumber", new ArrayList<String>() {{
//            add(lwLoop.getNumStrNoB());
//        }}); //球
//        intent.putStringArrayListExtra("mode", new ArrayList<String>() {{
//            add(lwLoop.isSsq() ? "双色球 单式" : "大乐透 单式");
//        }}); //玩法及模式
//        intent.putStringArrayListExtra("numMoney", new ArrayList<String>() {{
//            add("1注 2元");
//        }}); //注数及金额
//        startActivityForResult(intent, 0);
        finish();
    }

    //购彩记录
    //0-购买记录 1-追号记录 2-合买记录
    void getData() {
        String url = Constant_Url.GET_VOTE_RECORD;
        if (index == 1) {
            url = Constant_Url.GET_YET_RECORD;
        } else if (index == 2) {
            url = Constant_Url.GET_TEAM_BUY;
        }
        ll_empty.setVisibility(View.GONE);
        HashMap<String, String> pair = new HashMap<>();
        pair.put("user", userBean.getUsername());
        pair.put("password", PreferenceUtil.getPassword(this));
        pair.put("page", String.valueOf(page));
        pair.put("result", result);
        HttpManager.postAsyn(url, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                pr_listview.onRefreshComplete();
                showInternetOffLayout();
            }

            @Override
            public void onResponse(String response) {
                closeLoadingLayout();
                dissDialog();
                pr_listview.onRefreshComplete();
                GroupBuyBody userBean = FastOk.get(response, GroupBuyBody.class);
                if (userBean != null && userBean.getStatus() == 0 && userBean.getRecords().size() > 0) {
                    records.addAll(userBean.getRecords());
                    page++;
                }
                if (records.size() <= 0)
                    lwLoop.start();
                ll_empty.setVisibility(records.size() > 0 ? View.GONE : View.VISIBLE);
                adapter.notifyDataSetChanged();
            }
        }, pair);
    }

    @OnClick({R.id.rb_one, R.id.rb_two, R.id.rb_three})
    void onTabChange(View v) {
        String tag = v.getTag().toString();
        if (!result.equals(tag)) {
            page = 1;
            records.clear();
            adapter.notifyDataSetChanged();
            result = tag;
            showLoadingLayout(pr_listview);
            getData();
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        records.clear();
        page = 1;
        getData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        getData();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        checkLogin(new Callback() {
            @Override
            public void callbackSuccess() {
                super.callbackSuccess();
                if (index == 0) {//购买

                    String s = JSON.toJSONString(records.get(position - 1));

                    startActivity(new Intent(VoteRecordActivity.this, BuyDetailActivity.class)
                            .putExtra("bean", JSON.toJSONString(records.get(position - 1))));
                } else if (index == 1) {//追号
                    startActivity(new Intent(VoteRecordActivity.this, ChaseRecordListActivity.class)
                            .putExtra("bean", JSON.toJSONString(records.get(position - 1))));
                } else {//合买
                    startActivity(new Intent(VoteRecordActivity.this, GroupBuyDetailActivity.class)
                            .putExtra("bean", JSON.toJSONString(records.get(position - 1)))
                            .putExtra("from", GroupBuyDetailActivity.RECORD)
                    );
                }

            }
        });
    }

    //出现数据加载失败异常之后的重试
    @Override
    public void OnRetry(String btnMessage) {
        showLoadingLayout(pr_listview);
        getData();
    }


}
